<template>
    <base-breadcrumb :breadcrumb="!isAudit">
        <a-card>
            <titleName title="基本信息" />
            <a-form-model
                ref="ruleForm"
                :model="form"
                :rules="rules"
                :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
                :wrapper-col="{ lg: { span: 16 }, sm: { span: 16 } }"
            >
                <a-row :gutter="24">
                    <a-col :md="16" :sm="16">
                            <a-form-model-item label="所属单位" prop="projectId" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }">
                                <org-tree-select v-model="form.projectId" disabled isAutoSelectFirst checkStrictly @select="selectOrg" @getProjectInfo="getProjectInfo"></org-tree-select>
                            </a-form-model-item>
                        </a-col>
                    <!-- <a-col :md="8" :sm="8">
                        <a-form-model-item label="所属分公司" prop="branchComId">
                            <SelectSubCompany
                                :isDefaultSelected="pageType == 'add'"
                                v-model="form.branchComId"
                                placeholder="请选择"
                                disabled
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="所属项目" prop="projectId">
                            <SelectProject
                                :isDefaultSelected="pageType == 'add'"
                                v-model="form.projectId"
                                placeholder="请选择"
                                :form="form"
                                :is-clear="id == ''"
                                key-value="branchComId"
                                disabled
                                @selectChange="(e) => (
                                    form.projectDeptId = e.projectDeptId)"
                            />
                        </a-form-model-item>
                    </a-col> -->
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="退回申请人" prop="returnApplierId">
                            <SelectPersonByProject
                                :is-org="true"
                                v-model="form.returnApplierId"
                                :org-id="form.projectDeptId"
                                :currentLabel.sync="form.returnApplier"
                                :show-search="true"
                                mode="combobox"
                                placeholder="请选择"
                                :disabled="pageType == 'look'"
                                option-label-prop="children"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="身份证号码" prop="returnApplierIDCard">
                            <BaseInput
                                v-model="form.returnApplierIDCard"
                                :disabled="pageType == 'look'"
                                placeholder="请输入"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="申请人岗位" prop="postInfo">
                            <SelectProjectJob
                                v-model="form.postInfo"
                                :projectDeptId="form.projectDeptId"
                                :isClear="id == ''"
                                :disabled="pageType == 'look'"
                            />
                            <!-- <BaseInput :disabled="pageType == 'look'" placeholder="请输入" v-model="form.bankAccount" /> -->
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="银行账号" prop="bankAccount">
                            <BaseInput v-model="form.bankAccount" :disabled="pageType == 'look'" placeholder="请输入" />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="开户行名称" prop="accountBankName">
                            <BaseInput
                                v-model="form.accountBankName"
                                :disabled="pageType == 'look'"
                                placeholder="请输入"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="24" :sm="24">
                        <a-form-model-item label="申请原因" prop="applyReason">
                            <BaseTextarea
                                v-model="form.applyReason"
                                :disabled="pageType == 'look'"
                                placeholder="请输入"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col v-if="pageType != 'look'" :md="24" :sm="24">
                        <a-form-model-item label="申请人承诺书扫描件">
                            <upload-list
                                :business-code="'BM26'"
                                :upload-arrys.sync="form.fileInfoVOList"
                                multiple
                                @fileArrysData="handleFileUploaded"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col v-else :md="24" :sm="24">
                        <a-form-model-item label="申请人承诺书扫描件">
                            <file-link :file-list="form.fileInfoVOList" />
                        </a-form-model-item>
                    </a-col>
                </a-row>
            </a-form-model>
        </a-card>
        <a-card v-if="pageType == 'look' && form.financeAuditVO">
            <titleName title="公司财务资金部意见" />
            <a-form-model
                ref="ruleForm1"
                :model="form.financeAuditVO"
                :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
                :wrapper-col="{ lg: { span: 16 }, sm: { span: 16 } }"
            >
                <a-row :gutter="24">
                    <a-col :md="24" :sm="24">
                        <a-form-model-item label="" class="item">
                            该同志原有项目风险金按《项目部人员风险金预留分配表》中核定的金额
                            <a-form-model-item
                                :colon="false"
                                label=" "
                                prop="creditReturnAmount"
                                :style="{ display: 'inline-block' }"
                            >
                                <a-input-number
                                    v-model="form.financeAuditVO.creditReturnAmount"
                                    :min="0"
                                    disabled
                                    style="width: 350px; margin-top: -34px"
                                    placeholder="请输入"
                                />
                            </a-form-model-item>
                            元已全部预留。
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="24" :sm="24">
                        <a-form-model-item label="审批意见" prop="financeOpinions">
                            <BaseTextarea v-model="form.financeAuditVO.financeOpinions" disabled placeholder="请输入" />
                        </a-form-model-item>
                    </a-col>
                </a-row>
            </a-form-model>
        </a-card>
        <!-- v-if="taskDefKey == 'GS_SWGLBJL_AUDIT'" -->
        <a-card v-if="pageType == 'look' && form.commercialAuditVO">
            <titleName title="公司商务管理部" />
            <a-form-model
                ref="ruleForm2"
                :model="form.commercialAuditVO"
                :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
                :wrapper-col="{ lg: { span: 16 }, sm: { span: 16 } }"
            >
                <a-row :gutter="24">
                    <a-col :md="24" :sm="24">
                        <a-form-model-item label="" class="item">
                            根据《商务管理手册》规定，建议将该同志原来在项目预留风险金
                            <a-form-model-item
                                :colon="false"
                                label=" "
                                prop="returnAmount"
                                :style="{ display: 'inline-block' }"
                            >
                                <a-input-number
                                    v-model="form.commercialAuditVO.returnAmount"
                                    :min="0"
                                    disabled
                                    style="width: 350px; margin-top: -34px"
                                    placeholder="请输入"
                                />
                            </a-form-model-item>
                            元退回本人。
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="24" :sm="24">
                        <a-form-model-item label="审批意见" prop="commercialOpinions">
                            <BaseTextarea
                                v-model="form.commercialAuditVO.commercialOpinions"
                                disabled
                                placeholder="请输入"
                            />
                        </a-form-model-item>
                    </a-col>
                </a-row>
            </a-form-model>
        </a-card>
        <div v-if="pageType != 'look'" class="tool-btns page-btn-right-top">
            <a-button
                v-if="id != '' && form.auditStatus == 'DRAFT'"
                type="danger"
                :loading="loading.DELETE"
                @click="handleSave('DELETE')"
            >
                删除草稿
            </a-button>
            <a-button
                v-if="form.auditStatus == 'REJECTED'"
                type="primary"
                :loading="loading.REJECTED"
                @click="handleSave('REJECTED')"
            >
                保存
            </a-button>
            <a-button v-else type="primary" :loading="loading.DRAFT" @click="handleSave('DRAFT')"> 保存草稿 </a-button>
            <a-button type="primary" :loading="loading.SUBMITTED" @click="handleSave('SUBMITTED')"> 提交 </a-button>
            <a-button type="primary" @click="handleClose"> 关闭 </a-button>
        </div>
        <div v-else class="tool-btns page-btn-right-top">
            <BasePrintButton
                v-if="form.auditStatus == 'PAST'"
                type="primary"
                :before-print-fn="checkPersonalRiskReturnPrint"
            />
            <a-button v-if="checkVisibleInDetail" type="primary" class="ml20" @click="handleClose"> 关闭 </a-button>
        </div>
        <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
    </base-breadcrumb>
</template>
<script>
import {
    getPersonalRiskReturn,
    addPersonalRiskReturn,
    editPersonalRiskReturn,
    delPersonalRiskReturn,
    checkPersonalRiskReturn,
    checkPersonalRiskReturnPrint
} from '@/api/businessAffairs/riskRefund'
import { getOrganizePeopleList } from '@/api/safetySupervision/emergencyDrill'
import { getSelectListByType } from '@/api/businessAffairs/common.js'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import { isAttachment, checkVisibleInDetail } from '@/utils/util'
import { getInfoByStaffId } from '@/api/commons'
import UploadList from '@/components/UploadList'
import BasePrintButton from '@/components/BasePrintButton' // 打印按钮
import SelectPersonByProject from '@/components/Select/SelectPersonByProject' // 分公司
import SelectProjectJob from '@/components/Select/SelectProjectJob' // 项目
export default {
    name: 'a' + Date.now(),
    components: {
        SelectSubCompany,
        SelectProject,
        UploadList,
        BasePrintButton,
        SelectPersonByProject,
        SelectProjectJob
    },
    data() {
        const bankAccount = (rule, value, callback) => {
            const reg = /^(\d{16}|\d{19})$/
            if (!reg.test(value)) {
                callback(new Error('请输入正确的银行卡号'))
            } else {
                callback()
            }
        }
        return {
            checkVisibleInDetail: checkVisibleInDetail(this),
            loading: {
                DELETE: false,
                DRAFT: false,
                SUBMITTED: false,
                REJECTED: false
            },
            fetchingOrganizePeopleList: false,
            organizePeopleList: [],
            form: {
                returnApplierId: '',
                financeAuditVO: null,
                commercialAuditVO: null,
                returnApplierIDCard: '',
                projectDeptId: void 0,
                returnApplierId: void 0,
                projectId:null
            },

            rules: {
                branchComId: [{ required: true, message: '请选择分公司' }],
                projectId: [{ required: true, message: '请选择项目' }],
                bankAccount: [{ required: true, validator: bankAccount, trigger: 'blur' }],
                returnApplierId: [{ required: true, message: '请输入' }],
                accountBankName: [{ required: true, message: '请输入' }],
                returnApplierIDCard: [{ required: true, message: '请输入' }],
                applyReason: [{ required: true, message: '请输入' }],
                postInfo: [{ required: true, message: '请选择岗位' }]
            },
            id: '',

            pageType: '',
            //获取流程配置值
            processConfig: null,
            //点击提交发送流程配置值
            setProcessConfig: null,
            businessId: null
        }
    },
    props: {
        isAudit: {
            // 是否作为审批详情
            type: Boolean,
            default: false
        }
    },
    watch: {
        isAudit: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.$nextTick(() => {
                        this.pageType = 'look'
                    })
                }
            }
        }
    },
    async mounted() {
        if (this.$route.query.id) {
            this.id = this.$route.query.id
            console.log(this.id)
            this.checkPersonalRiskReturnReq()
        }else{
            this.form.projectId = this.$userInfo().currentPost.projectId;
        }
        this.pageType = this.$route.query.pageType
        if (this.pageType == 'look') {
            this.$route.meta.title = '个人风险金返还查看'
        } else {
            this.$route.meta.title = this.id == '' ? '个人风险金返还新增' : '个人风险金返还编辑'
        }
      //获取通过获取流程配置值
       this.processConfig = await this.$getConfigFn('comm_pre_reserve_risk_fund_return_apply')
    },
    methods: {
        //选择单位
        selectOrg(val) {
            if (val && val.length) {
                this.form.branchComId = val[val.length - 2].orgId;
            }
        },
        //获取项目详情
        getProjectInfo(e) {
            this.form.projectDeptId = e.projectDeptOrgId
        },
        checkPersonalRiskReturnPrint() {
            return checkPersonalRiskReturnPrint({ id: this.id }).then((res) => {
                console.log(res)
                return res[1].data.content
            })
        },
        changeEmployeeId(e) {
            this.getOrgEmployeeByUser(e)
        },
        async getOrgEmployeeByUser(id) {
            try {
                const employee = await getInfoByStaffId(id)

                if (employee.data.idCard) {
                    this.form.returnApplierIDCard = employee.data.idCard
                }

                console.log(this.formInfo)
            } catch (err) {
                console.error(err)
            }
        },
        //获取项目下的人员列表
        getOrganizePeopleList() {
            console.log(this.form)
            this.$nextTick(() => {
                this.form.returnApplierId = '' // 清空退回申请人
                let params = {
                    id: this.form.projectId
                }
                this.organizePeopleList = []
                this.fetchingOrganizePeopleList = true
                getOrganizePeopleList(params).then((res) => {
                    this.fetchingOrganizePeopleList = false
                    let obj = {}
                    res.data = res.data.reduce((cur, next) => {
                        obj[next.employeeId] ? '' : (obj[next.employeeId] = true && cur.push(next))
                        return cur
                    }, []) //设置cur默认类型为数组，并且初始值为空的数组
                    console.log(res.data)
                    this.organizePeopleList = res.data || []
                })

                console.log(this.organizePeopleList)
            })
        },
        async checkPersonalRiskReturnReq() {
            const [err, res] = await checkPersonalRiskReturn({ id: this.id })
            if (!err) {
                this.form = { ...this.form, ...res.data }
                this.getOrganizePeopleList()
                this.$nextTick(() => {
                    this.form.returnApplierId = res.data?.returnApplierId || ''
                })
            }
        },
        handleFileUploaded(list) {
            this.form.fileInfoVOList = [...list]
        },
        validateForm() {
            let flag = false
            this.$refs.ruleForm.validate((valid) => {
                if(!valid) {
                  this.$message.warning("请填写完所有必填项信息")
                }
                flag = valid
            })
            return flag
        },
        async delPersonalRiskReturn(params) {
            const [err, res] = await delPersonalRiskReturn(params)
            if (!err) {
                this.$message.success('成功')
                this.handleClose()
            }
        },
        // 处理增、删、改操作
        async handleSave(status) {
            this.setProcessConfig = null;
            if (status != 'DELETE') {
                if (!this.validateForm()) return
                if (isAttachment(this, status, this.form.fileInfoVOList)) return
            }
            if (this.loading[status]) return

            const params = {
                ...this.form,
                auditStatus: status
                // id: this.$route.query.id || void 0,
            }
            const { pageType } = this.$route.query
            const fn = pageType === 'edit' ? editPersonalRiskReturn : addPersonalRiskReturn
            const delParams = {id:params.id,type:1}
            const map = {
                DELETE: delPersonalRiskReturn,
                DRAFT: fn,
                SUBMITTED: fn,
                REJECTED: fn
            }
            if (status == 'DELETE') {
                let that = this
                this.$confirm({
                    title: '温馨提示',
                    content: '确定是否删除数据？',
                    okText: '确认',
                    okType: 'danger',
                    cancelText: '取消',
                    onOk: () => {
                        return that.delPersonalRiskReturn(delParams)
                    }
                })
            } else {
                this.submitApprovalConfirm(status =='SUBMITTED'?this.processConfig:6, async (flag)=>{
                  if(!flag) {
                    this.loading[status] = false
                    return
                  }
                  this.loading[status] = true
                const [err, res] = await map[status](params)
                if (!err) {
                    this.$message.success('成功')
                   if(status =='SUBMITTED') {
                    //提交时，返回id
                        this.businessId = res.data.id;
                        this.setProcessConfig = this.processConfig;
                        return
                    }else{
                    this.handleClose()
                 }
                }

                this.loading[status] = false
                })
            }
        },
        handleClose() {
            if (this.isAudit) {
                window.close()
            } else {
                this.$multiTab.close(this.$route.fullpath)
            }
        }
    }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.tool-btns {
    display: flex;
    justify-content: flex-end;
    @{deep} .ant-btn + .ant-btn {
        margin-left: 12px;
    }
}
.tx {
    color: rgba(0, 0, 0, 0.85);
    font-size: 14px;
    margin-left: 30px;
}
.return-ratio .ant-form-item-children .ant-form-explain {
    margin-left: 230px;
}
.inputStyl {
    border-color: #e4ac0b;
    background-color: #fff9e8;
}
.item {
    margin-left: 60px;
}
.item .ant-form-item {
    margin-top: -28px;
}
.ant-form {
    min-height: 400px;
}
</style>
